<?php 
/**
 * Mail  plugin
 *
 * @version		$Id: Mail.php 74 2009-03-08 19:37:21Z dr_drsh $
 * @package		Joomla
 * @subpackage	JForms
 * @copyright	Copyright (C) 2008 Mostafa Muhammad. All rights reserved.
 * @license		GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

class JFormSPluginMail {
    static public function initMailer() {

        require_once join(DIRECTORY_SEPARATOR,array(JPATH_BASE,'libraries','Swift','swift_required.php'));
    }
    function searchRecords($form, $fields, $start, $rpp, $keyword ) {
//Do Nothing
    }

    function onFormCreate( &$form, $elementPlugins ) {
//Do Nothing
    }

    function onFormSave( &$form, $elementPlugins ) {
//Do Nothing
    }

    function onFormDelete( $form, $additionalParameters ) {
//Do Nothing
    }

    function deleteRecords( $form , $idsArray ) {
//Do Nothing
        return false;
    }

    function getRecords( $form, $ids ) {
//Do Nothing
        return null;
    }

    function saveRecord( $form, $data, VA_Form_Form $jForm = null ) {

        global $JFormGlobals;
        $pManager = $JFormGlobals['JFormsPlugin'];

//Send out an E-mail to Administrators and User (Based on Form settings)
        $dataText = "<br />";
        $formName = $form->title;

        $pluginSettings  = $form->storagePluginParameters['Mail'];

        $fields = indexByHash( $form->fields );

        $adminMessage = $pluginSettings['AdminText'];
        $userMessage  = $pluginSettings['ConfrimText'];

        foreach($fields as $key => $f ) {

//If field has no storage requirments
            if( !count($pManager->element_plugins[$f->type]->storage) ) {
//Ignore it
                continue;
            }

            if( array_key_exists( $key, $data ) ) {

//Translate Raw data into readable format
                $d = $pManager->invokeMethod('translate',JFORM_PLUGIN_ELEMENT,
                        array($f->type), array( $f, $data[$key] ) );
                $dataText .= $f->parameters['label'] ." : ".$d."<br />";
                $fieldPlaceholder = '{FIELD='.strtoupper($f->parameters['label']).'}';
                $adminMessage = str_replace( $fieldPlaceholder, $d, $adminMessage );
                $userMessage  = str_replace( $fieldPlaceholder, $d, $userMessage  );
            }
        }

//Look for user E-mail field
        $userEmail = '';
        foreach($form->fields as $f) {

            if( array_key_exists('isUserEmail',$f->parameters) && $f->parameters['isUserEmail'] == true ) {
                $hash = $f->parameters['hash'];
//Grab it from current record
                $userEmail = $data[$hash];
                break;
            }
        }

        if( $pluginSettings['SendAdmin'] ) {

            self::initMailer();
            $mailer = Swift_Mailer::newInstance(Swift_SendmailTransport::newInstance());
            /* @var $message Swift_Message */
            $message = Swift_Message::newInstance()
                    ->setSubject(JText::_('New entry added'))
                    ->setFrom(array('forms@hiled.ru' => 'Сайт '.$_SERVER['HTTP_HOST']));

            $AdminMails = explode(',',$pluginSettings['AdminMail']);

            $adminMessage = str_replace('{FORM_NAME}' ,$formName, $adminMessage );
            if(null !== $jForm) {
                $adminMessage = str_replace('{ENTRY_DATA}',self::prepareMessage($jForm, $message), $adminMessage );
            } else $adminMessage = str_replace('{ENTRY_DATA}',$dataText, $adminMessage );
            $adminMessage = str_replace("\r\n", "<br />", $adminMessage );
            $adminMessage = str_replace("\n"  , "<br />", $adminMessage );
            $adminMessage = str_replace("\r"  , "<br />", $adminMessage );

            $to = array();
            foreach($AdminMails as $address )
                $to[trim($address)] = 'Менеджер сайта '.$_SERVER['SERVER_NAME'];
            $message->setTo($to);
            $message->setBody($adminMessage, 'text/html');
            $attachments = array();
            $bytesLeft = 10485760;
            /*if(null !== $jForm) {
                $elements = $jForm->getElements();
                foreach($elements as $e) {
                    if(($e instanceof VA_Form_FormElement_File) &&
                            $e->getValue() &&
                            file_exists($e->getValue()) &&
                            (0 < $bytesLeft - filesize($e->getValue()))) {
                        $bytesLeft -= filesize($e->getValue());
                        $attachments[] = Swift_Attachment::fromPath($e->getValue(), 'multipart/mixed');
                        $message->attach($attachments[count($attachments)-1]);
                    }
                }
            }*/
            try {
                $mailer->send($message);
            } catch (Swift_TransportException $e) {
                echo 'Произошла непредвиденная критическая ошибка с почтовым ящиком получателя. Убедительно просим <a href="javascript: history.go(-1);">повторить отправку через 1 минуту</a>.';
            }
        }
    }
    protected static function prepareMessage(VA_Form_Form $form, Swift_Message $message) {
        $table = '';
        $elements = $form->getElements();
        /* @var $e VA_Form_FormElement */
        foreach($elements as $e) {
            $v = $e->getPrintableValue();
            $d = array($e->getLabel());
            if(!empty($v)) {
                if(($e instanceof VA_Form_FormElement_MultiFile)) {
                    $helper = new VA_Form_ViewHelper_Email_MultiFile();
                    $helper->setElement($e);
                    $v = $helper->wrap();
                } elseif (($e instanceof VA_Form_FormElement_File)) {
                    $helper = new VA_Form_ViewHelper_Email_File();
                    $helper->setElement($e);
                    $v = $helper->wrap();
                }
                $dontPrint = ($e instanceof VA_Form_FormElement_Button) ||
                        ($e instanceof VA_Form_FormElement_Hidden) ||
                        ($e instanceof VA_Form_FormElement_Captcha) ||
                        ($e instanceof VA_Form_FormElement_HtmlBlock);
                if(false === $dontPrint) {
                    $d[] = $v;
                    $table .= self::wrapLine($d);
                }
            }
        }
        $format = '<table>%s</table>';
        return sprintf($format, $table);
    }
    /**
     * Заворачивает в табличку
     *
     * @param array $data
     */
    protected static function wrapLine($data) {
        $return = '';
        foreach ($data as $value)
            $return .= sprintf('<td>%s</td>', $value);
        return sprintf('<tr>%s</tr>', $return);
    }
}